package com.jz.digital.database;


import android.annotation.SuppressLint;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.jz.digital.BuildConfig;
import com.jz.digital.bean.DaoMaster;
import com.jz.digital.bean.DaoSession;
import com.jz.digital.utils.LogUtils;

import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.EncryptedDatabase;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.query.QueryBuilder;

import java.io.File;

/**
 * @Author: ym
 * @ClassName: GreenDaoManager
 * @Description: 数据库管理类
 * @Package: com.ido.life.database
 * @CreateDate: 2020/4/30 0030 12:00
 */
public class GreenDaoManager {
    public static final String DB_NAME = "handheld_terminal.db";//数据库名称
    @SuppressLint("StaticFieldLeak")
    private final static GreenDaoManager mGreenDaoManager = new GreenDaoManager();//多线程访问
    private DaoMaster.DevOpenHelper mHelper;
    private static DaoMaster mDaoMaster;
    private static DaoSession mDaoSession;
    private Context context;
    private final static String PASSWORD = "MYdJ9BaaET5KcObzpEGmEbg27BdZ4n";

    /**
     * 使用单例模式获得操作数据库的对象
     */
    public static GreenDaoManager getInstance() {
        return mGreenDaoManager;
    }

    /**
     * 初始化Context对象
     */
    public void init(Context context) {
        this.context = context;
    }

    /**
     * 判断数据库是否存在，如果不存在则创建
     */
    private DaoMaster getDaoMaster() {
        if (null == mDaoMaster) {
            mHelper = new DaoMaster.DevOpenHelper(context, DB_NAME, null) {
                @Override
                public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                    if (!processDataBaseUpgrade(new StandardDatabaseWraper(db), oldVersion, newVersion)) {
                        super.onUpgrade(db, oldVersion, newVersion);
                    }
                }

                @Override
                public void onUpgrade(Database db, int oldVersion, int newVersion) {
                    if (db instanceof EncryptedDatabase &&
                            processDataBaseUpgrade(new StandardDatabaseWraper((EncryptedDatabase) db), oldVersion, newVersion)) {
                    } else {
                        super.onUpgrade(db, oldVersion, newVersion);
                    }
                }
            };
            if (BuildConfig.DEBUG) {
                mDaoMaster = new DaoMaster(mHelper.getWritableDb());
                LogUtils.d("GreemDaoManager", DB_NAME + " 数据库不加密");
            } else {
                mDaoMaster = new DaoMaster(getWritableDatabase());
                LogUtils.d("GreemDaoManager", DB_NAME + " 数据库加密");
            }
        }
        return mDaoMaster;
    }

    /**
     * 处理数据库升级
     */
    private boolean processDataBaseUpgrade(StandardDatabaseWraper databaseWrapper, int oldVersion, int newVersion) {
        boolean success = false;
        try {
            success = DatabaseUpgradeUtil.upgradeDatabase(databaseWrapper, oldVersion, newVersion);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success;
    }

    /**
     * 如果对已有数据进行加密，需要先对原有数据库进行加密操作
     *
     * @return
     */
    private Database getWritableDatabase() {
        try {
            return mHelper.getEncryptedWritableDb(PASSWORD);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                //尝试加密后再打开
                DBEncrypt.getInstences().encrypt(context, DB_NAME, PASSWORD);
                return mHelper.getEncryptedWritableDb(PASSWORD);
            } catch (Exception e2) {
                e2.printStackTrace();
                File file = context.getDatabasePath(DB_NAME);
                file.delete();
                logOutWhenError();
                mHelper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
                return mHelper.getEncryptedWritableDb(PASSWORD);
            }
        }
    }

    /**
     * 当数据库解密发生异常，就清除缓存退回到登录注册页面
     */
    private void logOutWhenError() {
    }

    /**
     * 完成对数据库的增删查找
     */
    public DaoSession getDaoSession() {
        if (null == mDaoSession) {
            synchronized (GreenDaoManager.this) {
                if (null == mDaoMaster) {
                    synchronized (GreenDaoManager.this) {
                        mDaoMaster = getDaoMaster();
                    }
                }
                mDaoSession = mDaoMaster.newSession(IdentityScopeType.None);
            }
        }
        return mDaoSession;
    }

    /**
     * 设置debug模式开启或关闭，默认关闭
     */
    public void setDebug(boolean flag) {
        QueryBuilder.LOG_SQL = flag;
        QueryBuilder.LOG_VALUES = flag;
    }

    /**
     * 关闭数据库
     */
    public void closeDataBase() {
        closeHelper();
        closeDaoSession();
    }

    public void closeDaoSession() {
        if (null != mDaoSession) {
            mDaoSession.clear();
            mDaoSession = null;
        }
    }

    public void closeHelper() {
        if (mHelper != null) {
            mHelper.close();
            mHelper = null;
        }
    }
}
